package com.aizhixin.lab.project.course.service;

import com.aizhixin.lab.account.dto.AccountDTO;
import com.aizhixin.lab.common.core.ApiReturnConstants;
import com.aizhixin.lab.common.core.DataValidity;
import com.aizhixin.lab.project.course.entity.*;
import com.aizhixin.lab.project.course.repository.*;
import com.aizhixin.lab.project.template.core.TaskFileType;
import com.aizhixin.lab.project.template.data.ModuleTaskData;
import com.aizhixin.lab.project.template.domain.DeleteDomain;
import com.aizhixin.lab.project.template.domain.ModuleTaskDomain;
import com.aizhixin.lab.project.template.domain.ModuleTaskFileDomain;
import com.aizhixin.lab.project.template.domain.ProjectRoleDomain;
import com.aizhixin.lab.project.template.entity.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

@Slf4j
@Service
@Transactional
public class TeacherModuleTaskService {
    @Autowired
    private TeacherModuleTaskRepository taskRepository;
    @Autowired
    private TeacherModuleTaskFileRepository taskFileRepository;
    @Autowired
    private TeacherProjectModuleRepository moduleRepository;
    @Autowired
    private TeacherProjectRepository projectRepository;
    @Autowired
    private TeacherTaskWorkOrderRepository workOrderRepository;
    @Autowired
    private TeacherExercisesRepository teacherExercisesRepository;
    /**
     * 查看模块下所有任务列表
     * @param id
     * @return
     */
    public List<ModuleTaskDomain> findTaskByModuleId(String id) {
        List<TeacherModuleTask> taskList = taskRepository.findByModuleIdAndDeleteFlagOrderByTaskNoAsc(id, DataValidity.VALID.getState());
        List<ModuleTaskDomain> taskDomainList = new ArrayList<>();
        for (TeacherModuleTask moduleTask : taskList) {
            ModuleTaskDomain moduleTaskDomain = new ModuleTaskDomain();
            BeanUtils.copyProperties(moduleTask, moduleTaskDomain);
            List<ProjectRoleDomain> roleDomainList = new ArrayList<>();
            for (ProjectRole projectRole : moduleTask.getProjectRoleList()) {
                ProjectRoleDomain roleDomain = new ProjectRoleDomain();
                BeanUtils.copyProperties(projectRole, roleDomain);
                roleDomainList.add(roleDomain);
            }
            Integer count = teacherExercisesRepository.countByTaskId(moduleTaskDomain.getId());
            if (count>0){
                moduleTaskDomain.setIsExist(true);
            }else {
                moduleTaskDomain.setIsExist(false);
            }
            moduleTaskDomain.setProjectRoleDomainList(roleDomainList);
            taskDomainList.add(moduleTaskDomain);
        }
        return taskDomainList;
    }
    public List<ModuleTaskData> findTask(String id) {
        List<TeacherModuleTask> taskList = taskRepository.findByModuleIdAndDeleteFlagOrderByTaskNoAsc(id, DataValidity.VALID.getState());
        List<ModuleTaskData> taskDomainList = new ArrayList<>();
        for (TeacherModuleTask moduleTask : taskList) {
            ModuleTaskData moduleTaskDomain = new ModuleTaskData();
            BeanUtils.copyProperties(moduleTask, moduleTaskDomain);
            taskDomainList.add(moduleTaskDomain);
        }
        return taskDomainList;
    }
    /**
     * 查看任务详情
     * @param id
     * @return
     */
    public ModuleTaskDomain findTaskInfo(String id, AccountDTO dto) {
        TeacherModuleTask task = taskRepository.findOne(id);
        ModuleTaskDomain moduleTaskDomain = new ModuleTaskDomain();
        BeanUtils.copyProperties(task, moduleTaskDomain);
        List<ProjectRoleDomain> roleDomainList = new ArrayList<>();
        List<ModuleTaskFileDomain> taskImages = new ArrayList<>();
        List<ModuleTaskFileDomain> teachingMaterial = new ArrayList<>();
        List<ModuleTaskFileDomain> videoFileList = new ArrayList<>();
        for (ProjectRole projectRole : task.getProjectRoleList()) {
            ProjectRoleDomain roleDomain = new ProjectRoleDomain();
            BeanUtils.copyProperties(projectRole, roleDomain);
            roleDomainList.add(roleDomain);
        }
        moduleTaskDomain.setProjectRoleDomainList(roleDomainList);
        List<TeacherModuleTaskFile> teacherModuleTaskFileList;
        if (dto.getRole().equals("student")){
            teacherModuleTaskFileList=taskFileRepository.findByTaskIdAndDeleteFlagAndIsHide(task.getId(), DataValidity.VALID.getState(),false);
        }else {
            teacherModuleTaskFileList = taskFileRepository.findByTaskIdAndDeleteFlag(task.getId(), DataValidity.VALID.getState());
        }
        for (TeacherModuleTaskFile moduleTaskFile : teacherModuleTaskFileList) {
            ModuleTaskFileDomain domain = new ModuleTaskFileDomain();
            BeanUtils.copyProperties(moduleTaskFile, domain);

            if (TaskFileType.image.getIntValue().equals(moduleTaskFile.getFileType())) {
                taskImages.add(domain);
            } else if (TaskFileType.teachingMaterial.getIntValue().equals(moduleTaskFile.getFileType())) {
                teachingMaterial.add(domain);
            } else {
                videoFileList.add(domain);
            }
        }
        moduleTaskDomain.setVideoFileList(videoFileList);
        moduleTaskDomain.setTaskImages(taskImages);
        moduleTaskDomain.setTeachingMaterial(teachingMaterial);
        return moduleTaskDomain;
    }

    /**
     * 保存任务
     * @param domain
     * @return
     */
    public String save(ModuleTaskDomain domain) {
        Boolean isNew = false;
        if (null == domain.getId() || "".equals(domain.getId())) {
            domain.setId(UUID.randomUUID().toString());
            isNew = true;
        }
        List<TeacherModuleTaskFile> moduleTaskFileList = new ArrayList<>();
        if (domain.getTaskImages() != null) {
            for (ModuleTaskFileDomain taskFileDomain : domain.getTaskImages()) {
                TeacherModuleTaskFile moduleTaskFile = new TeacherModuleTaskFile();
                BeanUtils.copyProperties(taskFileDomain, moduleTaskFile);
                moduleTaskFile.setTaskId(domain.getId());
                moduleTaskFile.setFileType(TaskFileType.image.getIntValue());
                moduleTaskFile.setId(UUID.randomUUID().toString());
                moduleTaskFile.setCreatedDate(new Date());
                moduleTaskFileList.add(moduleTaskFile);
            }
        }
        if (domain.getTeachingMaterial() != null) {
            for (ModuleTaskFileDomain taskFileDomain : domain.getTeachingMaterial()) {
                TeacherModuleTaskFile moduleTaskFile = new TeacherModuleTaskFile();
                BeanUtils.copyProperties(taskFileDomain, moduleTaskFile);
                moduleTaskFile.setTaskId(domain.getId());
                moduleTaskFile.setFileType(TaskFileType.teachingMaterial.getIntValue());
                moduleTaskFile.setId(UUID.randomUUID().toString());
                moduleTaskFile.setCreatedDate(new Date());
                moduleTaskFileList.add(moduleTaskFile);
            }
        }
        if (domain.getVideoFileList() != null) {
            for (ModuleTaskFileDomain taskFileDomain : domain.getVideoFileList()) {
                TeacherModuleTaskFile moduleTaskFile = new TeacherModuleTaskFile();
                BeanUtils.copyProperties(taskFileDomain, moduleTaskFile);
                moduleTaskFile.setTaskId(domain.getId());
                moduleTaskFile.setFileFirstImg(taskFileDomain.getFileFirstImg());
                moduleTaskFile.setFileType(TaskFileType.taskVideo.getIntValue());
                moduleTaskFile.setId(UUID.randomUUID().toString());
                moduleTaskFile.setCreatedDate(new Date());
                moduleTaskFileList.add(moduleTaskFile);
            }
        }
        List<ProjectRole> projectRoles = new ArrayList<>();
        if (domain.getProjectRoleDomainList() != null) {
            for (ProjectRoleDomain roleDomain : domain.getProjectRoleDomainList()) {
                ProjectRole projectRole = new ProjectRole();
                BeanUtils.copyProperties(roleDomain, projectRole);
                projectRoles.add(projectRole);
            }
        }
        if (isNew) {
            TeacherModuleTask moduleTask = new TeacherModuleTask();
            BeanUtils.copyProperties(domain, moduleTask);
            Integer num = taskRepository.countByModuleIdAndDeleteFlag(domain.getModuleId(), DataValidity.VALID.getState());
            moduleTask.setTaskNo(num+1);
            moduleTask.setProjectRoleList(projectRoles);
            moduleTask.setDeleteFlag(DataValidity.VALID.getState());
            moduleTask.setCreatedDate(new Date());
            moduleTask.setWorkOrderNum(0);
            taskRepository.save(moduleTask);
            taskFileRepository.save(moduleTaskFileList);
            TeacherProjectModule projectModule = moduleRepository.findOne(moduleTask.getModuleId());
            if (!Objects.isNull(projectModule)) {
                projectModule.setTaskNum(projectModule.getTaskNum()+1);
                moduleRepository.save(projectModule);
            }
            return moduleTask.getId();
        }
        TeacherModuleTask one = taskRepository.findOne(domain.getId());
        domain.setWorkOrderNum(one.getWorkOrderNum());
        BeanUtils.copyProperties(domain, one);
        one.setProjectRoleList(projectRoles);
        taskRepository.save(one);
        taskFileRepository.deleteByTaskId(one.getId());
        taskFileRepository.save(moduleTaskFileList);
        return domain.getId();
    }

    /**
     * 删除任务
     * @param deleteDomain
     * @return
     */
    public Map<String, Object> delete(DeleteDomain deleteDomain) {
        Map<String, Object> result = new HashMap<String, Object>();
        Integer workOrderNum = workOrderRepository.countByTaskIdAndDeleteFlag(deleteDomain.getId(),DataValidity.VALID.getState());
        if (workOrderNum > 0) {
            result.put(ApiReturnConstants.SUCCESS, false);
            result.put(ApiReturnConstants.ERROR, "请先删除子任务");
        } else {
            TeacherModuleTask moduleTask = taskRepository.findOne(deleteDomain.getId());
            if (!Objects.isNull(moduleTask)) {
                TeacherProject project = projectRepository.findOne(deleteDomain.getProjectId());
                moduleTask.setDeleteFlag(DataValidity.INVALID.getState());
                taskRepository.save(moduleTask);
                Integer num =0;
                if (!Objects.isNull(project)) {
                    num = taskRepository.countByModuleIdAndDeleteFlag(project.getId(), DataValidity.VALID.getState());
                    project.setTaskNum(project.getTaskNum()-1);
                    projectRepository.save(project);
                    updateSort(moduleTask.getModuleId());

                }
                TeacherProjectModule projectModule = moduleRepository.findOne(moduleTask.getModuleId());
                if (!Objects.isNull(projectModule)) {
                    projectModule.setTaskNum(num);
                    moduleRepository.save(projectModule);
                }
                result.put(ApiReturnConstants.SUCCESS, true);
                result.put(ApiReturnConstants.DATA, "删除成功");
            }
        }
        return result;
    }

    /**
     * 修改模块下的任务顺序
     * @param moduleId
     */
    public void updateSort(String moduleId) {
        List<TeacherModuleTask> moduleTaskList = taskRepository.findByModuleIdAndDeleteFlagOrderByTaskNoAsc(moduleId, DataValidity.VALID.getState());
        for (int i = 0; i < moduleTaskList.size(); i++) {
            moduleTaskList.get(i).setTaskNo(i + 1);
        }
        taskRepository.save(moduleTaskList);
    }
    public void updateSort(List<String> ids){
        int i=1;
        for (String id : ids) {
            TeacherModuleTask moduleTask = taskRepository.findByIdAndDeleteFlag(id, DataValidity.VALID.getState());
            moduleTask.setTaskNo(i);
            taskRepository.save(moduleTask);
            i++;
        }
    }
}
